import 'package:flutter/material.dart';

class Olympic07 extends StatefulWidget {
  Olympic07({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _Olympic07State createState() => _Olympic07State();
}

class _Olympic07State extends State<Olympic07> {
  final List<Map> metalInfoList = [
    {
      'flag': Image.asset('assets/images/olympic/07/CHN.jpg'),
      'country': "中国",
      'gold_medal': 38,
      'silver_medal': 32,
      'bronze_medal': 18,
      'total': 88,
    },
    {
      'flag': Image.asset('assets/images/olympic/07/USA.jpg'),
      'country': "美国",
      'gold_medal': 39,
      'silver_medal': 41,
      'bronze_medal': 33,
      'total': 113,
    },
    {
      'flag': Image.asset('assets/images/olympic/07/JPN.jpg'),
      'country': "日本",
      'gold_medal': 27,
      'silver_medal': 14,
      'bronze_medal': 17,
      'total': 58,
    },
  ];

  Map currSortOrder = {
    'gold_medal': 'ASC',
    'silver_medal': 'ASC',
    'bronze_medal': 'ASC',
    'total': 'ASC',
  };
  String currKey = 'gold_medal';

  _sortListView(String? key) {
    setState(() {
      if (key != null) {
        currKey = key;
      }
    });
  }

  _getSortedList(String sortKey) {
    if (currSortOrder[sortKey] == "ASC") {
      currSortOrder[sortKey] = "DESC";
      metalInfoList.sort((a, b) => doCompare(b, a, sortKey));
    } else {
      currSortOrder[sortKey] = "ASC";
      metalInfoList.sort((a, b) => doCompare(a, b, sortKey));
    }
    //return scoreList;
  }

  int doCompare(Map a, Map b, String sortKey) {
    int ret = 0;
    List keys = ["gold_medal", "silver_medal", "bronze_medal", "total"];
    int count = 0;
    int index = keys.indexOf(sortKey);
    while (ret == 0 && count < keys.length) {
      String key = keys[index % keys.length];
      ret = a[key].compareTo(b[key]);
      index++;
      count++;
    }
    return ret;
  }

  Container _rowTilte() {
    return Container(
      child: Row(
        children: <Widget>[
          Container(
            width: 80,
            child: Text('国家/地区'),
          ),
          TextButton(
              onPressed: () {
                _sortListView('gold_medal');
              },
              child: Text('金牌')),
          TextButton(
              onPressed: () {
                _sortListView('silver_medal');
              },
              child: Text('银牌')),
          TextButton(
              onPressed: () {
                _sortListView('bronze_medal');
              },
              child: Text('铜牌')),
          TextButton(
              onPressed: () {
                _sortListView('total');
              },
              child: Text('奖牌数')),
        ],
      ),
    );
  }

  Container _createListView(String sortKey) {
    _getSortedList(sortKey);
    return Container(
        height: 150,
        child: ListView.builder(
          itemCount: metalInfoList.length,
          //itemExtent: 30,
          padding: EdgeInsets.all(10),
          itemBuilder: (context, index) {
            return Row(
              children: <Widget>[
                Container(
                  width: 30,
                  child: metalInfoList[index]['flag'],
                ),
                Container(
                  width: 40,
                  child: Text(metalInfoList[index]['country'].toString()),
                  //alignment: Center,
                ),
                Container(
                  width: 40,
                  child: Text(metalInfoList[index]['gold_medal'].toString()),
                ),
                Container(
                  width: 40,
                  child: Text(metalInfoList[index]['silver_medal'].toString()),
                ),
                Container(
                  width: 40,
                  child: Text(metalInfoList[index]['bronze_medal'].toString()),
                ),
                Container(
                  width: 40,
                  child: Text(metalInfoList[index]['total'].toString()),
                ),
              ],
            );
          },
        ));
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the Olympic07 object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          children: <Widget>[
            _rowTilte(),
            _createListView(currKey),
          ],
        ),
      ),
    );
  }
}
